package com.chengyu.core.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.chengyu.core.dto.tencent.SceneEmpowerReqDTO;
import com.chengyu.core.dto.tencent.SceneSaveReidDataReqDTO;
import com.chengyu.core.saasopenai.OpenApiHttpReq;
import com.chengyu.core.saasopenai.SaasOpenApiConfig;
import com.chengyu.core.saasopenai.SaasOpenApiHttpTool;
import com.chengyu.core.saasopenai.saaSRestTemplateConfig;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 对接tencent平台接口
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class HttpRequestService {

    private final SaasOpenApiConfig saasOpenApiConfig;
    private final saaSRestTemplateConfig restTemplateConfig;

//    private final PlatformConfig platformConfig;

    /**
     * 获取上传用户领取低碳奖励记录的访问地址
     *
     * @return
     */
//    private String getUploadMemberBehaviorUrl() {
//        String url = platformConfig.getDomain() + platformConfig.getUploadMemberBehaviorAPI();
//        if (StrUtil.isBlank(url)) {
//            throw new IllegalArgumentException("配置文件数据异常");
//        }
//        return url;
//    }

    /**
     * 获取用户减碳量出账/入账的访问地址
     *
     * @return
     */
//    private String getMemberAccReduceCarbonInOrOutUrl() {
//        String url = platformConfig.getDomain() + platformConfig.getUploadMemberBehaviorAPI();
//        if (StrUtil.isBlank(url)) {
//            throw new IllegalArgumentException("配置文件数据异常");
//        }
//        return url;
//    }

    /**
     * 获取签名请求头
     *
     * @return
     */
    private String getAuthToken() {
//        String token = "TC3-HMAC-SHA256 + ' '  'Credential=' + SecretId + ', ' +\n" +
//                "    'SignedHeaders=' + SignedHeaders + ', ' +\n" +
//                "    'Signature=' + Signature";
        return "";
    }

    /**
     * 上传用户领取低碳奖励记录
     *
     * @param dto
     */
//    public void uploadMemberBehavior(MemberBehaviorRecordRequestDTO dto) {
//        String url = getUploadMemberBehaviorUrl();
//        Long timeStamp = new Date().getTime();
//
//        String res = HttpUtil.createPost(url)
//                .header("Timestamp", String.valueOf(timeStamp))
//                .header("Authorization", String.valueOf(timeStamp))
//                .body(JSONUtil.parseObj(dto).toString()).execute().body();
//        JSONObject resJson = JSONUtil.parseObj(res);
//        String code = resJson.getStr("code");
//        if (!"0000".equals(code)) {
//            log.error("【上传用户领取低碳奖励记录】失败,请求结果：{}", resJson);
//            return;
//        }
//    }

    /**
     * 获取用户减碳量出账/入账
     *
     * @param dto
     */
//    public MemberAccReduceCarbonInOrOutResponseDTO getMemberAccReduceCarbonInOrOut(MemberAccReduceCarbonInOrOutRequestDTO dto) {
//        MemberAccReduceCarbonInOrOutResponseDTO result = new MemberAccReduceCarbonInOrOutResponseDTO();
//        String url = getMemberAccReduceCarbonInOrOutUrl();
//
//
//        String res = HttpUtil.createPost(url).header("", "").body(JSONUtil.parseObj(dto).toString()).execute().body();
//        JSONObject resJson = JSONUtil.parseObj(res);
//        String code = resJson.getStr("code");
//        if (!"00000".equals(code)) {
//            log.error("【用户减碳量出账/入账】失败,请求结果：{}", resJson);
//            throw new BusinessException("接口请求失败");
//        }
//        JSONObject data = resJson.getJSONObject("data");
//        result = JSONUtil.toBean(data, MemberAccReduceCarbonInOrOutResponseDTO.class);
//        return result;
//    }


    /**
     * 推送减排量到tencent
     * @param sceneSaveReidDataReqDTO
     * @return
     * @throws Exception
     */
    public void postReduceCarbonToTencent(SceneSaveReidDataReqDTO sceneSaveReidDataReqDTO) throws Exception {
        sceneSaveReidDataReqDTO.setSceneCode(saasOpenApiConfig.getUploadReduceCarbonSceneCode());
        sceneSaveReidDataReqDTO.setSceneName(saasOpenApiConfig.getUploadReduceCarbonSceneName());
        OpenApiHttpReq.OpenApiHttpReqBuilder builder = OpenApiHttpReq.builder()
                .url(saasOpenApiConfig.getUrl() + saasOpenApiConfig.getUploadReduceCarbonUrl())
                .httpMethod(HttpMethod.POST)
                .header(ImmutableMap.of(saasOpenApiConfig.getHeaderName(), saasOpenApiConfig.getHeaderValue()))
                .body(JSON.toJSONString(sceneSaveReidDataReqDTO))
                .timestamp(new Date());
        ResponseEntity<String> res = SaasOpenApiHttpTool.callHttp(builder.build(), saasOpenApiConfig, restTemplateConfig.restTemplate());
        // 得到一个完整的响应体
        JSONObject entries = JSONUtil.parseObj(res);
        log.debug("【推送减排量到tencent】请求结果：{}",entries.getJSONObject("body"));
    }

    /**
     * 碳碳星球授权回调结果推送数据到tencent
     * @param sceneEmpowerReqDTO
     * @throws Exception
     */
    public void postTanTanCallBackResultToTencent(SceneEmpowerReqDTO sceneEmpowerReqDTO) throws Exception {

        sceneEmpowerReqDTO.setSceneCode(saasOpenApiConfig.getTantanAuthCallbackSceneCode());
        sceneEmpowerReqDTO.setSceneId(saasOpenApiConfig.getTantanAuthCallbackSceneId());
        OpenApiHttpReq.OpenApiHttpReqBuilder builder = OpenApiHttpReq.builder()
                .url(saasOpenApiConfig.getUrl() + saasOpenApiConfig.getTantanAuthCallbackUrl())
                .httpMethod(HttpMethod.POST)
                .header(ImmutableMap.of(saasOpenApiConfig.getHeaderName(), saasOpenApiConfig.getHeaderValue()))
                .body(JSON.toJSONString(sceneEmpowerReqDTO))
                .timestamp(new Date());
        ResponseEntity<String> res = SaasOpenApiHttpTool.callHttp(builder.build(), saasOpenApiConfig, restTemplateConfig.restTemplate());

        // 得到一个完整的响应体
        JSONObject entries = JSONUtil.parseObj(res);
        log.debug("【碳碳星球授权回调结果推送数据到tencent】请求结果：{}",entries.getJSONObject("body"));
    }

}
